<?php

namespace app\api\logic;

use think\facade\Db;
use app\data\util\HttpUtil;
use think\exception\ValidateException;
use think\facade\Cache;
use app\api\logic\FeiShuTalkLogic;
use app\api\logic\FeiShuMessageLogic;


class ApiAdvggLogic extends BasicLogic
{
    public function __construct()
    {

    }
    /**
    * @desc    获取谷歌token
    * @date    2024/11/16
    * @author  zhangheng
    */
    public function GetggToken($params)
    {
        
    }

    /**
    * @desc    获取谷歌广告信息
    * @date    2024/11/16
    * @author  zhangheng
    */
    public function GetggAdInfo($params)
    {
        $type = $params['type']??2;
        $advertiser_id = $params['advertiser_id']??"";
        $where2 = [];
        if(!empty($advertiser_id)){
            $where2['advertiser_id'] = $advertiser_id;
        }
        switch ($type) {
            case '1':
                $advaccount = table('advaccount')
                    ->where('platform_id',2)
                    ->where('status',1)
                    ->where($where2)
                    ->where('updatetime_automatic_last','>=','2024-05-01')
                    ->order('integrated_time asc')
                    ->find();
                // 以广告账户维度
                if(!empty($advaccount)){
                    $this->integrated_get($advaccount);
                    //修改状态
                    $update = [];
                    $update['updatetime_automatic_last'] = date('Y-m-d', strtotime($advaccount['updatetime_automatic_last'])- 24 * 3600);
                    //重置成当前日期
                    $lastUpdateTime = strtotime($advaccount['updatetime_automatic_last']);
                    $tenDaysAgo = time() - 3600*24*5;
                    if((int)$lastUpdateTime <= (int)$tenDaysAgo && $advaccount['last_status'] == 1){
                        $update['updatetime_automatic_last'] = date('Y-m-d', time() - timezone());
                    }
                    $tenDaysAgo2 = time() - 3600*24*90;
                    if((int)$lastUpdateTime <= (int)$tenDaysAgo2 && $advaccount['last_status'] == 0){
                        $update['last_status'] = 1;
                    }
                    $update['integrated_time'] = time();
                    table('advaccount')
                        ->where('id',$advaccount['id'])
                        ->update($update);
                        
                }
                break;
            case '2':
                $advaccount = table('advaccount')
                    ->where('platform_id',2)
                    ->where('status',1)
                    ->where($where2)
                    // ->where('updatetime_automatic','<=',date('Y-m-d', time() - timezone() - 1*600))
                    ->order('integrated_time_new asc')
                    ->order('integrated_time asc')
                    ->find();
                    
                // 每天实时更新
                if(!empty($advaccount)){
                    $this->integrated_get($advaccount);
                    //修改状态
                    $update = [];
                    $update['integrated_time_new'] = time();
                    table('advaccount')
                        ->where('id',$advaccount['id'])
                        ->update($update);
                }
                break;
            default:
        }
        return $this->jsonMessage(200,true,'获取成功');
    }
    /**
    * @desc    拉取广告信息
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function integrated_get($advaccount)
    {
        $google_ads_token = Db::name('google_ads_token')->where('id',1)->value('access_token');
        $iscustom['access_token'] = $google_ads_token;
        $iscustom['developer_token'] = Config('Logisticskey.google_info.api_token') ?? "";

        $date_start = updatetime_automatic() ?? "";

        // $date_start = '2024-11-18';
        $date_start_gg = str_replace("-", "", $date_start);

        $advertiser_id = $advaccount['advertiser_id'] ?? "";
        $advertiser_id_gg = str_replace("-", "", $advertiser_id);

        $advertising_info = Db::name('advertising')
            ->where('advertiser_id', $advertiser_id)
            ->where('stat_time_day', date('Y-m-d H:i:s',strtotime($date_start)))
            ->where('type_name', "手动录入")
            ->find();
        if(!empty($advertising_info)){
            return true;
        }

        $url = Config('Logisticskey.google_info.customers_url').'/'.$advertiser_id_gg.'/googleAds:searchStream';
        $iscustom['login_customer_id'] = Config('Logisticskey.google_info.ads_id');
        $query = 'SELECT campaign.name, campaign.status, segments.device,
                    metrics.impressions, metrics.clicks, metrics.ctr,
                    metrics.average_cpc, metrics.cost_micros,
                    metrics.active_view_measurable_cost_micros
            FROM campaign
            WHERE metrics.cost_micros>0 and segments.date BETWEEN "'.$date_start_gg.'" AND "'.$date_start_gg.'"';
            
        $data = [
            'query' => $query,
        ];
        // halt($query);
        $return = HttpUtil::postUrlgg($url, $data,$iscustom);
        $results = $return[0]['results'] ?? [];
        // halt($results);
        $costMicros = 0;
        if (!empty($results)) {
            foreach ($results as $k=>$v) {
                $costMicros += $v['metrics']['costMicros'] ?? 0;
            }
        // halt($costMicros);

            $advertisingData = [
                'advertiser_id' => $advertiser_id,
                'platform_id' => $advaccount['platform_id'],
                'stat_time_day' => date('Y-m-d H:i:s',strtotime($date_start)),
                'spend'         => getRes($costMicros/1000000),
                'impressions' => 0,
                'stat_time' => strtotime($date_start),
                'type_name' => "API",
                'createtime' => time(),
            ];
            
            htmlLog(['AdvertisingApiLog'=>$advertisingData],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');

            $advertising_info = Db::name('advertising')
                ->where('advertiser_id', $advertisingData['advertiser_id'])
                ->where('stat_time_day', $advertisingData['stat_time_day'])
                // ->where('type_name', "API")
                ->find();
            if(!empty($advertising_info)){
                Db::name('advertising')->where('id',$advertising_info['id'])->update($advertisingData);
            }else{
                // Db::name('advertising')->insert($advertisingData);
            }
        }else{
            $loginfo = [];
            $loginfo['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
            $loginfo['advertiser_id'] = $advertiser_id;
            $loginfo['return'] = $results;
            htmlLog(['AdvertisingApiLog'=>$loginfo],OPERATE_LOG . date('Ym') . '/AdvertisingApiLog/' . date('Ymd') . '.txt');
        }
        
        return true;
    }



}
